package com.wujunshen.sample.service.impl;

import com.wujunshen.sample.entity.User;
import com.wujunshen.sample.service.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * User:  FrankWoo(吴峻申) <br>
 * Date:  2018/7/24 <br>
 * Time:  18:02 <br>
 * Email: frank_wjs@hotmail.com <br>
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    @Qualifier("masterMongoTemplate")
    private MongoTemplate masterMongoTemplate;

    @Resource
    @Qualifier("slaveMongoTemplate")
    private MongoTemplate slaveMongoTemplate;

    @Resource
    @Qualifier("masterGridFsTemplate")
    private GridFsTemplate masterGridFsTemplate;

    @Resource
    @Qualifier("slaveGridFsTemplate")
    private GridFsTemplate slaveGridFsTemplate;

    public User getUserOfMasterDB(String userName, String password) {
        Query query = Query.query(Criteria.where("userName")
                .is(userName).and("password").is(password));
        return masterMongoTemplate.findOne(query, User.class);
    }

    public User getUserOfSlaveDB(String userName, String password) {
        Query query = Query.query(Criteria.where("userName")
                .is(userName).and("password").is(password));
        return slaveMongoTemplate.findOne(query, User.class);
    }

    public void saveOfMasterDB(User user) {
        masterMongoTemplate.save(user);
    }

    public void saveOfSlaveDB(User user) {
        slaveMongoTemplate.save(user);
    }

    public boolean existsOfMasterDB(String userName) {
        Query query = Query.query(Criteria.where("userName").is(userName));
        return masterMongoTemplate.exists(query, User.class);
    }

    public boolean existsOfSlaveDB(String userName) {
        Query query = Query.query(Criteria.where("userName").is(userName));
        return slaveMongoTemplate.exists(query, User.class);
    }
}